package com.hongmeng.operater.service.newsAndVideo.impl;

import java.util.*;

import com.hongmeng.common.constant.Constants;
import com.hongmeng.common.core.domain.AjaxResult;
import com.hongmeng.common.utils.*;
import com.hongmeng.framework.web.service.PermissionService;
import com.hongmeng.operater.domain.HmFile;
import com.hongmeng.operater.domain.aliyun.VodVideoEntity;
import com.hongmeng.operater.domain.newsAndVideo.HmVideoFile;
import com.hongmeng.operater.domain.newsAndVideo.entity.QueryVideoInfoEntity;
import com.hongmeng.operater.domain.newsAndVideo.entity.SaveVideoInfoEntity;
import com.hongmeng.operater.domain.newsAndVideo.entity.VideoDetailListEntity;
import com.hongmeng.operater.domain.newsAndVideo.entity.VideoFileInfoEntity;
import com.hongmeng.operater.mapper.HmFileMapper;
import com.hongmeng.operater.mapper.newsAndVideo.HmVideoExtMapper;
import com.hongmeng.operater.mapper.newsAndVideo.HmVideoFileExtMapper;
import com.hongmeng.operater.mapper.newsAndVideo.HmVideoFileMapper;
import com.hongmeng.operater.service.aliyun.IVodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hongmeng.operater.mapper.newsAndVideo.HmVideoMapper;
import com.hongmeng.operater.domain.newsAndVideo.HmVideo;
import com.hongmeng.operater.service.newsAndVideo.IHmVideoService;
import org.springframework.transaction.annotation.Transactional;

import static com.hongmeng.common.utils.file.FileUtils.checkFileSize;

/**
 * 视频信息Service业务层处理
 *
 * @author hongmeng
 * @date 2020-12-28
 */
@Service
@Slf4j
public class HmVideoServiceImpl implements IHmVideoService {

    @Autowired
    private HmVideoMapper hmVideoMapper;

    @Autowired
    private HmVideoExtMapper hmVideoExtMapper;

    @Autowired
    private HmFileMapper hmFileMapper;

    @Autowired
    private HmVideoFileMapper hmVideoFileMapper;

    @Autowired
    private HmVideoFileExtMapper hmVideoFileExtMapper;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private IVodService vodService;

    /**
     * 查询视频信息
     *
     * @param id 视频信息ID
     * @return 视频信息
     */
    @Override
    public HmVideo selectHmVideoById(Integer id) {
        return hmVideoMapper.selectHmVideoById(id);
    }

    @Override
    public AjaxResult selectHmVideoDetailedById(Integer id) {
        HmVideo hmVideo = hmVideoMapper.selectHmVideoById(id);
        String[] videoFileIds = hmVideo.getVideoFileIds().split(",");
        List<Map<String,Object>> mapList = new ArrayList<>();
        mapList.add(EntityToMapUtils.transBeanToMap(hmVideo));
        for (String videoFileId : videoFileIds) {
            VideoFileInfoEntity videoFile = hmVideoFileExtMapper.selectByVideoFileId(Integer.parseInt(videoFileId));
            //如果源文件为空则吧播放地址放进去
            if (videoFile.getVideoSourceUrl()==null || videoFile.getVideoSourceUrl().isEmpty()){
                AjaxResult videoResult = vodService.getPlayUserByVideoId(videoFile.getVideoId());
                if (AjaxResult.isSuccess(videoResult)){
                    VodVideoEntity vodVideoDto = (VodVideoEntity)videoResult.get("data");
                    videoFile.setVideoSourceUrl(vodVideoDto.getPlayUrlLD());
                }
            }

            mapList.add(EntityToMapUtils.transBeanToMap(videoFile));
        }
        return AjaxResult.success(mapList);
    }

    /**
     * 查询视频信息列表
     *
     * @param hmVideo 视频信息
     * @return 视频信息
     */
    @Override
    public List<HmVideo> selectHmVideoList(QueryVideoInfoEntity hmVideo) {
        //如果是运营管理，则只显示待审核信息（定时提交的只能看到当前时间之前的信息）
        if (permissionService.hasRole(Constants.ROLE_KEY.OP_ADMIN)&&
                !permissionService.hasRole(Constants.ROLE_KEY.ADMIN)){
            return hmVideoExtMapper.selectHmVideoListByAdmin(hmVideo);
        }
        //否，则显示全部信息
        return hmVideoExtMapper.selectHmVideoList(hmVideo);
    }

    @Override
    public List<VideoDetailListEntity> selectVideoDetailList(QueryVideoInfoEntity hmVideo) {
        //如果是运营管理，则只显示待审核信息（定时提交的只能看到当前时间之前的信息）
        List<VideoDetailListEntity> videoList;
        if (permissionService.hasRole(Constants.ROLE_KEY.OP_ADMIN)&&
                !permissionService.hasRole(Constants.ROLE_KEY.ADMIN)){
            videoList = hmVideoExtMapper.selectVideoDetailListByAdmin(hmVideo);
        }else{ //否，则显示全部信息
            videoList = hmVideoExtMapper.selectVideoDetailList(hmVideo);
        }
        for (VideoDetailListEntity videoInfo:videoList) {
            AjaxResult result = vodService.getPlayUserByVideoId(videoInfo.getVideoId());
            if (!AjaxResult.isSuccess(result)){
                continue;
            }
            VodVideoEntity videoEntity = (VodVideoEntity)result.get("data");
            videoInfo.setPlayUrlLD(videoEntity.getPlayUrlLD());
            videoInfo.setPlayUrlSD(videoEntity.getPlayUrlSD());
        }
        return videoList;
    }

    /**
     * 新增视频信息
     *
     * @param videoInfoEntity 视频信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult insertHmVideo(SaveVideoInfoEntity videoInfoEntity) {
        //新增视频状态必须为定时提交，待审核 或 已提交，待审核。
        if (!Constants.NEWS_AND_VIDEO_STATE.TIMING_SUBMIT.equals(videoInfoEntity.getVideoState()) &&
                !Constants.NEWS_AND_VIDEO_STATE.SUBMIT.equals(videoInfoEntity.getVideoState())) {
            log.info(MessageUtils.message("no.create.newsState"));
            return AjaxResult.error(MessageUtils.message("no.create.newsState"));
        }
        AjaxResult validationVideoInfo = checkVideoInfo(videoInfoEntity);
        if (!AjaxResult.isSuccess(validationVideoInfo)){
            return validationVideoInfo;
        }
        HmVideo hmVideoInfo = new HmVideo();
        BeanUtils.copyProperties(videoInfoEntity, hmVideoInfo);
        hmVideoInfo.setVideoType(videoInfoEntity.getVideoType());
        hmVideoInfo.setCreateBy(SecurityUtils.getUsername());
        hmVideoInfo.setCreateTime(DateUtils.getNowDate());
        hmVideoInfo.setUseType(Constants.VIDEO_USE_TYPE.NOT_USE);
        int count = hmVideoMapper.insertHmVideo(hmVideoInfo);
        log.info("新增视频信息共{}条",count);
        return AjaxResult.success();
    }

    /**
     * 修改视频信息
     *
     * @param videoInfoEntity 视频信息
     * @return 结果
     */
    @Transactional
    @Override
    public AjaxResult updateHmVideo(SaveVideoInfoEntity videoInfoEntity) {
        AjaxResult validationVideoInfo = checkVideoInfo(videoInfoEntity);
        if (!AjaxResult.isSuccess(validationVideoInfo)){
            return validationVideoInfo;
        }
        HmVideo hmVideoInfo = hmVideoMapper.selectHmVideoById(videoInfoEntity.getId());
        if (hmVideoInfo==null){
            log.info("修改视频失败，没有id为" + videoInfoEntity.getId() + "的视频");
            return AjaxResult.error(MessageUtils.message("no.videoId"));
        }
        BeanUtils.copyProperties(videoInfoEntity, hmVideoInfo);
        hmVideoInfo.setVideoType(videoInfoEntity.getVideoType());
        hmVideoInfo.setUpdateBy(SecurityUtils.getUsername());
        hmVideoInfo.setUpdateTime(DateUtils.getNowDate());
        //修改后审核状态改为已提交，待审核
        hmVideoInfo.setVideoState(Constants.NEWS_AND_VIDEO_STATE.SUBMIT);
        int count = hmVideoMapper.updateHmVideo(hmVideoInfo);
        log.info("更新视频信息共{}条",count);
        return AjaxResult.success();
    }

    /**
     * 批量删除视频信息
     *
     * @param ids 需要删除的视频信息ID
     * @return 结果
     */
    @Override
    public int deleteHmVideoByIds(Integer[] ids) {
        return hmVideoMapper.deleteHmVideoByIds(ids);
    }

    /**
     * 删除视频信息信息
     *
     * @param id 视频信息ID
     * @return 结果
     */
    @Override
    public int deleteHmVideoById(Integer id) {
        return hmVideoMapper.deleteHmVideoById(id);
    }

    @Transactional
    @Override
    public AjaxResult saveVideoFiles(String videoId,String sourceUrl) {
        HmVideoFile videoFile = new HmVideoFile();
        HmFile hmFile = new HmFile();
        if (sourceUrl==null||sourceUrl.isEmpty()){
            try {
                //阿里云通过videoId获取视频源地址
                AjaxResult videoDtoBaseResponse = vodService.getVodOriginalFileById(videoId);
                VodVideoEntity videoDto = (VodVideoEntity) videoDtoBaseResponse.get("data");
                videoFile.setVideoSourceUrl(videoDto.getDownloadFileUrl());
                hmFile.setFileUrl(sourceUrl);
                hmFile.setFileName(videoDto.getDownloadFileName());
                videoFile.setVideoTime(videoDto.getDuration());
                videoFile.setVideoSize(String.valueOf(checkFileSize(videoDto.getSize(),Constants.FILE_UNIT.KB)));
            } catch (Exception e) {
                videoFile.setVideoSourceUrl("");
                sourceUrl = "";
            }
        }else{
            videoFile.setVideoSourceUrl(sourceUrl);
            hmFile.setFileUrl(sourceUrl);
        }
        Date nowDate = DateUtils.getNowDate();
        String userName = SecurityUtils.getUsername();
        hmFile.setFileType(Constants.VIDEO_FORMAT.MP4);
        hmFile.setContentType("video/mp4");
        if (sourceUrl!=null&&!sourceUrl.isEmpty()){
            hmFile.setMd5(Md5Util.md5Hex(sourceUrl));
        }
        hmFile.setCreateTime(nowDate);
        hmFile.setCreateBy(userName);
        int count = hmFileMapper.insertHmFile(hmFile);
        log.info("新建文件信息共{}条，文件id为:{}",count,hmFile.getId());
        //创建视频文件信息
        videoFile.setVideoFileId(hmFile.getId());
        videoFile.setVideoId(videoId);
        videoFile.setCreateBy(userName);
        videoFile.setCreateTime(nowDate);
        count = hmVideoFileMapper.insertHmVideoFile(videoFile);
        log.info("新建视频文件信息共{}条,视频文件id为:{}",count,videoFile.getVideoFileId());
        return AjaxResult.success(hmFile);
    }

    @Override
    public AjaxResult examine(Integer id, boolean yesOrNo, String newsRemarks) {
        //只有拥有运营管理权限才能审核信息
        if (!permissionService.hasRole(Constants.ROLE_KEY.OP_ADMIN)){
            log.info("只有运营管理才能审核信息");
            return AjaxResult.error(MessageUtils.message("not.newsAdmin"));
        }
        HmVideo hmVideo = hmVideoMapper.selectHmVideoById(id);
        if (hmVideo == null) {
            log.info("审核视频失败，没有id为" + id + "的视频");
            return AjaxResult.error(MessageUtils.message("no.videoId"));
        }
        if (!Constants.NEWS_AND_VIDEO_STATE.SUBMIT.equals(hmVideo.getVideoState()) &&
                !Constants.NEWS_AND_VIDEO_STATE.TIMING_SUBMIT.equals(hmVideo.getVideoState())){
            log.info("当前信息状态不正确无法审核");
            return AjaxResult.error(MessageUtils.message("not.state"));
        }
        if (Constants.NEWS_AND_VIDEO_STATE.TIMING_SUBMIT.equals(hmVideo.getVideoState())){
            Date nowDate = DateUtils.getNowDate();
            if (hmVideo.getPubdate().compareTo(nowDate)>0){
                log.info("当前信息状态不正确无法审核");
                return AjaxResult.error(MessageUtils.message("not.state"));
            }
        }
        if (yesOrNo) {
            hmVideo.setVideoState(Constants.NEWS_AND_VIDEO_STATE.PASS_AND_RELEASE);
            hmVideo.setPubdate(DateUtils.getNowDate());
        } else {
            hmVideo.setVideoState(Constants.NEWS_AND_VIDEO_STATE.NOT_PASS);
        }
        hmVideo.setVideoRemarks(newsRemarks);
        int count = hmVideoMapper.updateHmVideo(hmVideo);
        log.info("审核视频信息共{}条", count);
        return AjaxResult.success("视频审核成功");
    }

    //验证参数是否正确
    private AjaxResult checkVideoInfo(SaveVideoInfoEntity videoInfoEntity) {
        if (videoInfoEntity.getId()!=null){
            HmVideo hmVideo = hmVideoMapper.selectHmVideoById(videoInfoEntity.getId());
            if (hmVideo==null){
                log.info("视频信息id:{0}不存在");
                return AjaxResult.error(MessageUtils.message("no.videoId",videoInfoEntity.getId()));
            }
        }
        if (videoInfoEntity.getVideoFileIds()==null){
            log.info("视频文件id不能为空");
            return AjaxResult.error(MessageUtils.message("not.null.videoFileId"));
        }
        String[] videoFileIdStr = videoInfoEntity.getVideoFileIds().split(",");
        HmFile file = hmFileMapper.selectHmFileById(videoInfoEntity.getThumbnailId());
        if (file == null) {
            log.info("缩略图不能为空");
            return AjaxResult.error(MessageUtils.message("no.null.thumbnailId"));
        }
        for (String videoFileId : videoFileIdStr) {
            HmVideoFile hmVideoFile = hmVideoFileMapper.selectHmVideoFileById(Integer.parseInt(videoFileId));
            if (hmVideoFile == null) {
                log.info("视频文件id:{}不存在",videoFileId);
                return AjaxResult.error(MessageUtils.message("no.videoFileId"),videoFileId);
            }
        }
        return AjaxResult.success();
    }
}
